<?php

namespace App\Helpers;

use App\Model\Resource;
use App\Model\UserPoster;
use App\Model\WineProduct;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Storage;
use Intervention\Image\ImageManager;

class ProductPoster
{
    public $qiniuPath;

    public function createByProduct($product_id,$user_id,$username="丁花花绘本")
    {
        $product = WineProduct::find($product_id);

        if (!$product) return false;

        $posterPath  = false;

        if (!$product->poster || $product->poster && strtotime($product->poster_create) >time()+3600*10){
            $posterPath = $this->createPost($product);
            $product->poster = $posterPath;
            $product->poster_create = date('Y-m-d H:i:s');
            $product->save();
        }

        if ($username){

            //没有则重新生成
            $up = new UserPoster();
            $up->obj_id = $product_id;
            $up->user_id = $user_id;
            $up->username = $username;
            $up->path = '';
            $up->type = 'product';
            $up->save();

            //如果更新了底图则更新海报
            if ($posterPath) {
                $posterPath = $this->addPosterUser($posterPath,$up->id,$username,$product->id);
                $up->path = $posterPath;
                $up->save();
                return $posterPath;
            }

            //查找用户生成的用户海报
            $item = DB::table('t_user_poster')->where('obj_id','=',$product_id)->where('user_id','=',$user_id)
                ->where('username','=',$username)
                ->where('type','=','product')
                ->whereNotNull('path')
                ->where('created_at','<',date('Y-m-d H:i:s',time()+21600))
                ->orderBy('created_at','desc')
                ->first();

            if ($item && $item->path) return $item->path;

            if($posterPath = $this->addPosterUser($product->poster,$up->id,$username,$product->id)){
                $up->path = $posterPath;
                $up->save();
                return $posterPath;
            }
        }
        return $posterPath;
    }

    public function createPost($product)
    {

        $root = storage_path('app/public/canvas/');
        @mkdir($root);
        $template_path = storage_path('app/template/');
        $filename = md5(time().str_random(32)).'.jpg';
        @mkdir(storage_path('app/public/poster'));

        $savePath = storage_path('app/public/poster/').$filename;

        $font_path = $template_path.'PingFang Regular.ttf';

        $manager =  new ImageManager(['driver' => 'imagick']);
        $img = $manager->make(storage_path('app/template/backgroud_1.jpg'))->resize(750,1334);

        //乐饮推荐语
        if ($product->letDrink_recom) {
            $a = mb_strpos($product->letDrink_recom,'，');
            $a = $a?$a:mb_strpos($product->letDrink_recom,',');

            $l = mb_strlen($product->letDrink_recom);
            $text = [];
            $sub = 0;
            if ($a && $a<6){
                $text[0] = mb_substr($product->letDrink_recom,0,$a+1);
                $sub = $a+1;
            }
            while ($sub<$l){
                $text[] = mb_substr($product->letDrink_recom,$sub,6);
                $sub+=6;
            }
            foreach ($text as $k=>$v){
                $img->text($v,118,265+$k*80,function ($font) use ($font_path) {
                    $font->file($font_path);
                    $font->size(48);
                    $font->valign('bottom');
                    $font->color('#222222');
                });
            }
        }

        //封面图片
        if ($cover = $product->covers()->first()){
            $cover = $manager->make($cover->imgSrv)->resize(271,500);
            $img->insert($cover,'top-right',60,135);

            //口味关键词
            $keywords = $product->drinkTasteKeywords;
            $start = 93;
            //$k_w = count($keywords) > 3 ?140:160;
            $k_w = count($keywords) > 3 ?28:36;
            foreach ($keywords as $k=>$keyword){
                $keywordPic = $manager->make($keyword->keyword_pic)->resize(45,45);
                $img->insert($keywordPic,'top-left',$start,699);
                $img->text($keyword->keyword,$start+53,728,function ($font) use ($font_path) {
                    $font->file($font_path);
                    $font->size(26);
                    $font->valign('bottom');
                    $font->color('#303030');
                });

                $kwl= mb_strlen($keyword->keyword);
                //$start = $start+$k_w;
                 $start = $start+78+ $kwl*$k_w;
            }
        }

        //圆角
        $yuanjao = $manager->make($template_path.'yuanjiao.png')->resize(130,50);

        $tag_l = 95;
        //消费场景
        if ($scenes = $product->scenes()->first()){
            $currentSceneName = $scenes->currentScene->name;
            $scenes_l = mb_strlen($currentSceneName);
            $tag_w1 = $scenes_l<=3?130:150;

            $t = $tag_l;
            $img->insert($yuanjao,'top-left',$tag_l,763);
            if ($tag_w1>130) {
                $img->insert($yuanjao,'top-left',$tag_l +23,763);
                $tag_l +=170;
            }else{
                $tag_l +=150;
            }
            $img->text($currentSceneName,intval($t+($tag_w1-$scenes_l*26)/2),798,function ($font) use ($font_path) {
                $font->file($font_path);
                $font->size(26);
                $font->valign('bottom');
                $font->color('#FFFFFF');
            });
        }

        //产品等级
        if ($grading = $product->wineGrading){

            $grading_l =mb_strlen($grading->name);
            $tag_w2 = $grading_l<=3?130:150;

            $t = $tag_l;
            $img->insert($yuanjao,'top-left',$tag_l,763);
            if ($tag_w2>130) {
                $img->insert($yuanjao,'top-left',$tag_l +23,763);
                $tag_l +=170;
            }else{
                $tag_l +=150;
            }

            $img->text($grading->name, intval($t+($tag_w2-$grading_l*26)/2),798,function ($font) use ($font_path) {
                $font->file($font_path);
                $font->size(26);
                $font->valign('bottom');
                $font->color('#FFFFFF');
            });
        }
        //菜系或口味
        $grading = $product->cuisines()->first();
        if (!$grading) $grading = $product->wineTastes;
        if ($grading){

            $grading_l =mb_strlen($grading->name);
            $tag_w3 = $grading_l<=3?130:150;

            $t = $tag_l;
            $img->insert($yuanjao,'top-left',$tag_l ,763);
            if ($tag_w3>130) {
                $img->insert($yuanjao,'top-left',$tag_l +23,763);
                $tag_l +=170;
            }else{
                $tag_l +=150;
            }

            $img->text($grading->name, intval($t+($tag_w3-$grading_l*26)/2),798,function ($font) use ($font_path) {
                $font->file($font_path);
                $font->size(26);
                $font->valign('bottom');
                $font->color('#FFFFFF');
            });
        }

        //中文名称
        $img->text($product->chname,92,870,function ($font) use ($font_path) {
            $font->file($font_path);
            $font->size(24);
            $font->valign('bottom');
            $font->color('#7e7e7e');
        });

        //产品名称
        $img->text($product->name,92,900,function ($font) use ($font_path) {
            $font->file($font_path);
            $font->size(24);
            $font->valign('bottom');
            $font->color('#7e7e7e');
        });
        //生产年份
        $img->text($product->vintage,92,930,function ($font) use ($font_path) {
            $font->file($font_path);
            $font->size(24);
            $font->valign('bottom');
            $font->color('#7e7e7e');
        });
        $img->text("|",170,930,function ($font) use ($font_path) {
            $font->file($font_path);
            $font->size(24);
            $font->valign('bottom');
            $font->color('#7e7e7e');
        });
        //酒庄名称
        $img->text($product->chateauName,197,930,function ($font) use ($font_path) {
            $font->file($font_path);
            $font->size(22);
            $font->valign('bottom');
            $font->color('#7e7e7e');
        });

        //小程序码
//        if (!$product->xcx_code){
//            $miniProgram  = app('wechat.mini_program');
//            $codePath = $miniProgram->app_code->getUnlimit($product->id)->saveAs(storage_path('app/public/xcx'),md5(time().str_random(32)).'.jpg');
//            $product->xcx_code = $codePath;
//            $product->save();
//        }
//
//        $codePath = storage_path('app/public/xcx/'.$product->xcx_code);
//        $cover = $manager->make($codePath)->resize(120,120);
//        $img->insert($cover,'top-left',58,1175);


        $img->save($savePath,100);

        $disk = Storage::disk('qiniu');
        $qiniu_path = 'letsDrink/poster/product/'.date('Ymd') .'/'.$filename;
        $this->qiniuPath = Resource::getQiniuSrv($qiniu_path);
        $disk->put($qiniu_path,file_get_contents($savePath));
        unlink($savePath);
        //unlink($codePath);
        return $this->qiniuPath;
    }

    public function addPosterUser($path,$userPosterId,$username,$productId)
    {
        $root = storage_path('app/public/poster');
        $date = date('Ymd');
        @mkdir($root);
        $root = $root.'/product';
        @mkdir($root);
        $root = $root.'/'.$date;
        @mkdir($root);

        $template_path = storage_path('app/template/');
        $filename = md5(time().str_random(32)).'.jpg';
        $savePath = $root.'/'.$filename;
        $outputPath = env('POSTER','https://api.letsdrink.com.cn/v2').'/storage/poster/product/'.$date.'/'.$filename;

        $font_path = $template_path.'PingFang Regular.ttf';

        $manager =  new ImageManager(['driver' => 'imagick']);
        $img = $manager->make($path)->resize(750,1334);
        $img->text('@'.$username.' 有点想喝这款酒',60,1101,function ($font) use ($font_path) {
            $font->file($font_path);
            $font->size(24);
            $font->valign('bottom');
            $font->color('#7e7e7e');
        });

        //小程序码
        $miniProgram  = app('wechat.mini_program');
        $codePath = $miniProgram->app_code->getUnlimit($userPosterId)->saveAs(storage_path('app/public/xcx'),md5(time().str_random(32)).'.jpg');
        $codePath = storage_path('app/public/xcx/'.$codePath);
        $cover = $manager->make($codePath)->resize(120,120);
        $img->insert($cover,'top-left',58,1175);

        $img->save($savePath,100);
        unlink($codePath);

        if (file_exists($savePath)) {
            return $outputPath;
        }else{
            return false;
        }

//        $disk = Storage::disk('qiniu');
//        $qiniu_path = 'letsDrink/poster/user/'.date('Ymd') .'/'.$filename;
//        $this->qiniuPath = Resource::getQiniuSrv($qiniu_path);
//        $disk->put($qiniu_path,file_get_contents($savePath));
//        unlink($savePath);
//        return $this->qiniuPath;

    }

}
